package com.ahuzdw.com;

/**
 * Author: Zhang Dongwei
 * Date: 2021/12/16 16:25
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class _14_LongestCommonPrefix {
    public static void main(String[] args) {
        Solution solution = new _14_LongestCommonPrefix().new Solution();
//        String[] strs = {"flower","flow","flight"};
        String[] strs = {"flowerdua","flowerid","floweridulight"};
        String res = solution.longestCommonPrefix(strs);
        System.out.println(res);
    }

    class Solution {
        public String longestCommonPrefix(String[] strs) {
            int l = strs.length;
            System.out.println(l);
            int minl = 999;
            String minstr = "";
            String res = "";
            for(int i=0;i<l;i++) {
                if (strs[i].length()<minl){
                    minl = strs[i].length();
                    minstr = strs[i];
                }
            }
            for(int j=minl;j>0;j--){
                int count = 0;
                for(int k=0;k<l;k++){
//                    System.out.println("strs[k]:"+ strs[k]);
//                    System.out.println("strs[k].substring(0,j):"+ strs[k].substring(0,j));
//                    System.out.println("minstr.substring(0,j):"+ minstr.substring(0,j));
//                    count = 0;
                    if(strs[k].substring(0,j).equals(minstr.substring(0,j))){
                        count += 1;
//                        res = minstr.substring(0,j);
//                        return res;
                    }
                    System.out.println(count);
                    if(count == l){
                        res = minstr.substring(0,j);
                        return res;
                    }
                }

            }
            return res;
        }
    }
}
